package com.edocbase.desktop.plugins.mdairy.parts;

import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.graphics.Image;

import com.edocbase.biz.diary.entities.DiaryEntity;
import com.edocbase.desktop.lightweight.ui.LookAndFeel;
import com.edocbase.desktop.search.DiaryDocument;
import com.edocbase.entity.EntityManager;
import com.edocbase.entity.EntityManagerFactory;
import com.edocbase.entity.StoreException;

public class SearchResultDiaryProvider implements IDiaryProvider {
	private EntityManager<DiaryEntity> diaryManager = null;

	public SearchResultDiaryProvider() {
		super();
		diaryManager = EntityManagerFactory.getEntityManager(DiaryEntity.class);
	}

	@Override
	public String getTitle(DiaryDocument doc) {
		try {
			String id = doc.getDiaryId();
			DiaryEntity diary = getDiary(id);
			String title = diary.getTitle();
			return title;
		} catch (StoreException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String getDesc(DiaryDocument doc) {
		try {
			String id = doc.getDiaryId();
			DiaryEntity diary = getDiary(id);
			String desc = diary.getText();
			if (desc == null){
				desc = doc.getContent();
				if (!StringUtils.isEmpty(desc)){
					diary.setText(desc);
					diary.save();
				}
			}
			return desc;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Image getThumb(DiaryDocument doc) {
		Image img = LookAndFeel.getImage(getClass() ,"/images/mailtodriver.gif");
		img = LookAndFeel.getImage("e:\\1218316697762.jpg");
		return img;
	}

	public DiaryEntity getDiary(String id) throws StoreException{
		DiaryEntity diary = diaryManager.createQuery()
		.EQUALS(DiaryEntity.DIARY_FIELD_DIARY_ID, id).findOne();
		return diary;
	}
	
}
